<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class UserFile extends CMiniyunModel
{

    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return Yii::app()->params['tablePrefix'].'files';
    }
    
    public function getUserFileCount($ids){
        if ($ids=="") return array();
        $dbCommand = Yii::app()->db->createCommand("SELECT user_id,COUNT(*) as count FROM `".Yii::app()->params['tablePrefix']."files` where user_id in(".$ids.") GROUP BY user_id");
        return $dbCommand->queryAll();
    }
    
    public function getUsedSpace($ids){
        if ($ids=="") return array();
        $dbCommand = Yii::app()->db->createCommand("SELECT user_id,sum(file_size) as usedSpace FROM `".Yii::app()->params['tablePrefix']."files` where user_id in(".$ids.") GROUP BY user_id");
        return $dbCommand->queryAll();
    }

    
    public function deleteUserFile($userIds){
        if ($userIds!='' && strlen($userIds)>0){
            $data = $this->findAll("user_id in(".$userIds.")");            $versionIds = $this->getIds($data,"version_id");
            $fileIds = $this->getIds($data);
            $fileVersion = new FileVersion();
            $fileVersion->deleteFileVersion($versionIds);            $fileMeta = new FileMeta();
            $fileMeta->deleteFileMeta($userIds);            $shareFile = new ShareFile();
            $shareFile->deleteShareFile($fileIds);            $this->deleteAll("user_id in(".$userIds.")");        }
    }

    
    public function revertFile($fileIds){

        if ($fileIds==='' && strlen($fileIds)<=0)
        {
            return 0;
        }
        $models = $this->findAll("id in(".$fileIds.")");
        foreach ($models as $model) {
            $user_id    = $model['user_id'];
            $path       = $model['file_path'];
            $context    = $path;
                        $createFolder = new CreateFolder();
            $createFolder->_deviceId = 0;
            $createFolder->_userId   = $user_id;
            $pathInfo = CUtils::pathinfo_utf($path);
            
            try {
                $parentId  = $createFolder->handleCreateByPath($pathInfo["dirname"]);
            } catch (ApiException $e) {
                Yii::log($e->getMessage());
                continue;
            }
            
            $event_uuid = CUtils::random_string(46);
            $action     = 0;              if ($model['file_type'] == 0) {
                                                                                $this->_saveFileMeta($model);
                    $action = 3;
                    $context = array( "hash"  => $version['file_signature'],
                          "rev"   => (int)$model["version_id"],
                          "bytes" => (int)$model["file_size"]);
                    $context = serialize($context);
            }
            $event = new UserEvent();
            $event->CreateEvent($user_id, 0, $action, $path, $context, $event_uuid);
            $model['event_uuid'] = $event_uuid;
            $model["is_deleted"] = 0;
            $model->save();
        }

        return TRUE;

    }
    
    public function removedFile($fileIds){

        if ($fileIds==='' && strlen($fileIds)<=0)
        {
            return 0;
        }
        $ids='';
        $arr = array();
        $data = $this->findAll("id in(".$fileIds.")");
        foreach ($data as $key=>$value)
        {
                                                $moreData = $this->findAll("user_id=:type1 and file_path like :type2",
            array('type1'=>$value['user_id'], 'type2'=>$value['file_path']."%"));
            foreach ($moreData as $k=>$v)
            {
                $id = $v['id'];
                if (in_array($id, $arr))
                {
                                        continue;
                }
                
                if(strlen($ids)>0){
                    $ids = $ids.",";
                }
                array_push($arr,$id);
                $ids = $ids.$id;
            }
        }
        
        $models = $this->findAll("id in(".$ids.")");
        foreach ($models as $model) {
            
            $user_id    = $model['user_id'];
            $path       = $model['file_path'];
            $context = $path;
            $event_uuid = CUtils::random_string(46);
            $action     = 1;              $event = new UserEvent();
            
            if ($model['file_type'] == 0) {
                                                                                $this->_saveFileMeta($model);
            }
            $model['event_uuid'] = $event_uuid;
            $model["is_deleted"] = 1;
            $model->save();
            $event->CreateEvent($user_id, 0, $action, $path, $context, $event_uuid);
        }

        return true;

    }
    
    public function deletedFile($fileIds){

        if ($fileIds==='' && strlen($fileIds)<=0)
        {
            return 0;
        }
        $ids='';
        $arr = array();
        $data = $this->findAll("id in(".$fileIds.")");
        foreach ($data as $key=>$value)
        {
                                                $moreData = $this->findAll("user_id=:type1 and file_path like :type2",
            array('type1'=>$value['user_id'], 'type2'=>$value['file_path']."%"));
            foreach ($moreData as $k=>$v)
            {
               if ($v['is_deleted'] == 0) {
                    $user_id    = $v['user_id'];
                    $path       = $v['file_path'];
                    $context = $path;
                    $event_uuid = CUtils::random_string(46);
                    $action     = 1;                      $event = new UserEvent();
                    
                    if ($v['file_type'] == 0) {
                                                                                                                $this->_saveFileMeta($v);
                    }
                    $event->CreateEvent($user_id, 0, $action, $path, $context, $event_uuid);
                }
                
                $id = $v['id'];
                if (in_array($id, $arr))
                {
                                        continue;
                }

                if(strlen($ids)>0){
                    $ids = $ids.",";
                }
                array_push($arr,$id);
                $ids = $ids.$id;
            }
        }

        
        
                $shareFile = new ShareFile();
        $shareFile->deleteShareFile($ids);

        return $this->deleteAll("id in(".$ids.")");

    }

    
    public function updateFileName($id, $name, &$message)
    {
        $model = $this->findByAttributes(array('id'=>$id));
        if (empty($model))
        {
            $message = '获取文件信息失败, 更名失败';
            return false;
        }
        $oldPath                   = $model['file_path'];
        $model['file_name']        = $name;
        $model['file_path']        = dirname($model['file_path'])."/".$name;
                                $same = $this->findByAttributes(array('file_path'=>$model['file_path']));
        if ($same)
        {
            $message = '文件名已经存在, 更名失败';
            return false;
        }
        $time                      = (int)time();
        $model['file_update_time'] = $time;
        $path       = $model['file_path'];
        $context = $path;
        if ($model['file_type'] == 0)
        {
                                                $this->_saveFileMeta($model);
        } else
        {
                                                $moreFile = UserFile::model()->findAll("file_path like :type", array('type'=>$oldPath.'%'));
            foreach ($moreFile as $key=>$value)
            {
                                                                $index = strlen($model['file_path']);
                $value['file_path'] = substr_replace($value['file_path'], $model['file_path'], 0, $index);
                $s = UserFile::model()->updateAll(array(
                    	'file_path'        => $value['file_path'],
                        'file_update_time' => $time,
                        'updated_at'       => new CDbExpression('NOW()'),
                ), "id=".$value['id']);
                                
                if ($value['file_type'] == 0) {
                                                                                $this->_saveFileMeta($value);
                }
            }
        }
        
        $user_id    = $model['user_id'];
        
        $event_uuid = CUtils::random_string(46);
        $action     = 2;          $event = new UserEvent();
        $event->CreateEvent($user_id, 0, $action, $oldPath, $context, $event_uuid);
        $model['event_uuid'] = $event_uuid;
        $message = '文件更名成功';
        return $model->save(false);
    }
    
    private function _saveFileMeta($model)
    {
                                $fileMeta = FileMeta::model()->findByAttributes(array('file_path'=>$model['file_path'],'meta_key'=>'version'));
        if ($fileMeta)
        {
            $metaValue = $this->_createMeta(
            $model['version_id'],
            2,
            Yii::app()->session['user']['id'],
            Yii::app()->session['user']['nick'],
            $fileMeta['meta_value']
            );
        } else
        {
            $fileMeta = new FileMeta;
            $metaValue = $this->_createMeta(
            $model['version_id'],
            2,
            Yii::app()->session['user']['id'],
            Yii::app()->session['user']['nick']
            );
        }
        $fileMeta['file_path']  = $model['file_path'];
        $fileMeta['meta_key']    = 'version';
        $fileMeta['meta_value'] = $metaValue;
        $fileMeta->save();
    }

    private function _createMeta($versionID, $action, $userID, $userNick, $versions="a:0:{}")
    {
        $metas = is_null($versions)||empty($versions) ? "a:0:{}" : $versions;
        $meta               = array();
        $meta["type"]       = $action;
        $meta["version_id"] = $versionID;
        $meta["user_id"]    = $userID;
        $meta["user_nick"]  = $userNick;
        $meta["datetime"]   = date("Y-m-d H:i:s");
        $metas              = unserialize($metas);
        array_push($metas, $meta);
        return serialize($metas);
    }

    
    public function revertVersion($id, $version_id)
    {
        $version = FileVersion::model()->findByPk($version_id);
        $model = $this->findByPk($id);
        $time                = (int)time();
        $model['version_id'] = $version_id;
        $model['file_update_time'] = $time;
        $model['file_size'] = $version['file_size'];
        
                $user_id    = $model['user_id'];
        $path       = $model['file_path'];
        $event_uuid = CUtils::random_string(46);
        $action     = 4;          $context = array( "hash"  => $version['file_signature'],
                          "rev"   => (int)$model["version_id"],
                          "bytes" => (int)$model["file_size"]);
        
        
        $this->_saveFileMeta($model);
        $model['event_uuid'] = $event_uuid;
        $model->save();
        $event = new UserEvent();
        $event->CreateEvent($user_id, 0, $action, $path, serialize($context), $event_uuid);
    }


    
    public function revertFileAll()
    {
        $models = $this->findAllByAttributes(array('is_deleted'=> 1));
        foreach ($models as $model) {
            
            $user_id    = $model['user_id'];
            $path       = $model['file_path'];
            $context    = $path;
            $event_uuid = CUtils::random_string(46);
            $action     = 0;              if ($model['file_type'] == 0) {
                                                                                $this->_saveFileMeta($model);
                    $action = 3;
                    $version = FileVersion::model()->findByPk($model["version_id"]);
                    $context = array( "hash"  => $version['file_signature'],
                          "rev"   => (int)$model["version_id"],
                          "bytes" => (int)$model["file_size"]);
                    $context = serialize($context);
            }
            
            $model['event_uuid'] = $event_uuid;
            $model["is_deleted"] = 0;
            $model->save();
            $event = new UserEvent();
            $event->CreateEvent($user_id, 0, $action, $path, $context, $event_uuid);
        }
        return true;
    }

    
    public function deletedCount()
    {
        return $this->count('is_deleted=1');
    }

    
    public function officeCount()
    {
        $officeConditons = "";
        $officeTypes = Yii::app()->params['officeType'];
        $officeConditons = "'".implode("','",array_values($officeTypes))."'";
        return $this->count("version_id in(select id from ".Yii::app()->params['tablePrefix']."file_versions where mime_type in($officeConditons))");
    }
    
    public function getOfficeCount($userId)
    {
        $officeConditons = "";
        $officeTypes = Yii::app()->params['officeType'];
        $officeConditons = "'".implode("','",array_values($officeTypes))."'";
        return $this->count("version_id in(select id from ".Yii::app()->params['tablePrefix']."file_versions where mime_type in($officeConditons)) and user_id=? and is_deleted=0",array($userId));
    }
    
    public function imageCount()
    {
        return $this->count("version_id in(select id from ".Yii::app()->params['tablePrefix']."file_versions where mime_type like 'image%')");
    }
    
    public function getCount($userId){
        return $this->count("user_id=? and is_deleted=0",array($userId));
    }
    
    public function getImageCount($userId)
    {
        return $this->count("version_id in(select id from ".Yii::app()->params['tablePrefix']."file_versions where mime_type like 'image%') and user_id=? and is_deleted=0",array($userId));
    }
    
    public function getMusicCount($userId)
    {
        return $this->count("version_id in(select id from ".Yii::app()->params['tablePrefix']."file_versions where mime_type like 'audio%') and user_id=? and is_deleted=0",array($userId));
    }
    
    public function getVedioCount($userId)
    {
        return $this->count("version_id in(select id from ".Yii::app()->params['tablePrefix']."file_versions where mime_type like 'video%') and user_id=? and is_deleted=0",array($userId));
    }
    
    public function getAllFolderJson($userId){
        $items =  $this->findAll("user_id=? and file_type=1 and is_deleted=0",array($userId));
        $data = array();
        $first = Array();
        $first['name'] = "我的".Yii::app()->params['app']['name'];
        $first['aid'] = 1;
        $first['cid'] = "1_0";
        $first['pid'] = 0;
        $first['s'] = 0;
        $data['1_0'] = $first;

        foreach ($items as $index=>$item){
            $folder = array();
            $folder["name"]=$item["file_name"];
            $folder["aid"]="1";
            $folder["cid"]=$item["id"];
            if ($item["parent_file_id"] == 0){
                $folder["pid"]="1_0";
            }else{
                $folder["pid"]=$item["parent_file_id"];
            }
            	
            $folder["is_share"]="0";            $folder["s"]=$index;
            $folder["category_file_count"]="45";
            $folder["pick_code"]="";
            $folder["category_cover"]="";
            $data[$item["id"]]=$folder;
        }


        $retVal = array(
			"state"=>true,
			"data" =>$data,
			"msg"=>"",
			"msg_code"=>""
			);
			return json_encode($retVal);
    }


    
    public function getAllFolder($userId,$data = array()){
        $items =  $this->findAll("user_id=? and file_type=1 and is_deleted=0",array($userId));
        foreach ($items as $index=>$item){
            $folder = array();
            $folder["name"]=$item["file_name"];
            $folder["aid"]="1";
            $folder["cid"]=$item["id"];
            if ($item["parent_file_id"] == 0){
                $folder["pid"]="1_0";
            }else{
                $folder["pid"]=$item["parent_file_id"];
            }
            $folder["is_share"]="0";            $folder["s"]=$index;
            $folder["category_file_count"]="45";
            $folder["pick_code"]="";
            $folder["category_cover"]="";
            $data[$item["id"]]=$folder;
        }
        return $data;
    }


    
    public function getFileCount($fileId)
    {
        $condition = "is_deleted != 1 and parent_file_id=:parent_file_id and file_type = 0";
        $params    = array(':parent_file_id'=>$fileId);
        return $this->count($condition, $params);
    }

    
    public function getTrashCount($userId){
        return $this->count("user_id=? and is_deleted=1",array($userId));
    }


    
    public function getByFileName($userId, $fileName){
        return $this->find("user_id=? and file_name=?",array($userId,$fileName));
    }


    
    public function getByParentID($userId, $parent_file_id){
        return $this->findAll("user_id=? and parent_file_id=? and is_deleted=0",array($userId,$parent_file_id));
    }


    
    public function getFilesByIds($userId, $ids, $is_deleted = 0) {
        return $this->findAll("user_id={$userId} and id in ($ids) and is_deleted = $is_deleted");
    }

    
    public function getFilesByPath($path, $is_deleted = 0) {
        return $this->findAll(array('condition' => 'file_path like :file_path and is_deleted =:is_deleted order by id DESC',
                                    'params'    => array(':file_path'=>"$path/%", ':is_deleted' => $is_deleted)));
    }


    
    public function getChildrenFileByPath($path, $type = 0) {
        return $this->findAll(array('condition' => 'file_path like :file_path and file_type = :file_type order by id DESC',
                                    'params'    => array(':file_path'=>"$path/%", ":file_type" => $type)));
    }

    
    public function updateAllByParentPath($fromPath, $toPath, $userId) {
        $fromPath .= "/";
        $toPath   .= "/";
        $sql = "Update `".Yii::app()->params['tablePrefix']."files` SET file_path = ";
        $sql .= "CONCAT('$toPath', SUBSTRING(file_path,CHAR_LENGTH(:length) + 1))";
        $sql .= " WHERE file_path like '$fromPath%' and user_id = :user_id";

        $dbCommand = Yii::app()->db->createCommand($sql);
        $dbCommand->bindParam(":user_id", $userId);
        $dbCommand->bindParam(":length", $fromPath);
        return $dbCommand->execute();
    }


    
    public function getUserFolderImg($user_id, $parent_file_id, $start, $limit){
        
        return $this->findAllBySql("SELECT * FROM ".Yii::app()->params['tablePrefix']."files WHERE user_id=".$user_id." and is_deleted != 1 and parent_file_id=".$parent_file_id." and version_id in(select id from ".Yii::app()->params['tablePrefix']."file_versions where mime_type like 'image%') ORDER BY created_at desc LIMIT " . $start . "," . $limit);
    }
    
    
    public function getUserLocationImg($user_id, $limit = 45, $start = 0, $ids){
        return UserFile::model()->findAllBySql("SELECT * FROM " . Yii::app()->params['tablePrefix'] . "files WHERE user_id=" . $user_id . " and is_deleted != 1 and version_id in (" . $ids . ") ORDER BY created_at desc limit " . $start . ", " . $limit);
    }
}